package io.renren.membermanage.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.constant.BizSystemException;
import io.renren.membermanage.dto.UpdateModelLabelParam;
import io.renren.membermanage.entity.ModelLabel;
import io.renren.membermanage.mappper.ModelLabelMapper;
import io.renren.membermanage.service.ModelLabelService;
import org.springframework.stereotype.Service;

@Service
public class ModelLabelServiceImpl extends ServiceImpl<ModelLabelMapper, ModelLabel> implements ModelLabelService {

    @Override
    public boolean addModelLabel(UpdateModelLabelParam param) {
        verify(param);
        ModelLabel modelLabel = new ModelLabel();
        modelLabel.setId(IdWorker.getId());
        modelLabel.setLabelName(param.getLabelName());
        return this.save(modelLabel);
    }

    @Override
    public boolean updateModelLabel(UpdateModelLabelParam param) {
        verify(param);
        if (null == param.getId()) {
            throw new BizSystemException("请选择具体的标签！");
        }
        ModelLabel modelLabel = this.getById(param.getId());
        if (null == modelLabel) {
            throw new BizSystemException("当前标签已被删除！");
        }
        modelLabel.setLabelName(param.getLabelName());
        return this.updateById(modelLabel);
    }

    @Override
    public boolean deleteModelLabel(Long id) {
        ModelLabel modelLabel = this.getById(id);
        if (null == modelLabel) {
            throw new BizSystemException("当前标签已被删除！");
        }
        this.removeById(id);
        return false;
    }

    private void verify(UpdateModelLabelParam param){
        if (StrUtil.isBlank(param.getLabelName())){
            throw new BizSystemException("标签名不允许为空！");
        }
        LambdaQueryWrapper<ModelLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ModelLabel::getLabelName, param.getLabelName());
        wrapper.eq(ModelLabel::getDelFlag, "0");
        wrapper.ne(null != param.getId(), ModelLabel::getId, param.getId());
        if (this.exists(wrapper)) {
            throw new BizSystemException("当前标签已存在，请勿重复添加！");
        }
    }
}
